package com.xiang.utils;


import cn.binarywang.tools.generator.ChineseAddressGenerator;
import cn.binarywang.tools.generator.ChineseIDCardNumberGenerator;
import cn.binarywang.tools.generator.ChineseMobileNumberGenerator;
import cn.binarywang.tools.generator.ChineseNameGenerator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiang.config.EsConfig;
import com.xiang.domain.Customer;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建文档
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-29
 */
public class CreateDoc {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(CreateDoc.class);

    /**
     * 创建文档
     *
     * @throws JsonProcessingException json处理异常
     */
    @Test
    public void createDoc() throws IOException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(LocalDateTime.now());
        String idCard = ChineseIDCardNumberGenerator.getInstance().generate();
        Customer customer = new Customer(IdUtil.simpleUUID(),
                ChineseNameGenerator.getInstance().generate(),
                idCard,
                idCard.charAt(idCard.length() - 2) % 2 == 0 ? "女" : "男",
                IdcardUtil.getAgeByIdCard(idCard),
                ChineseMobileNumberGenerator.getInstance().generate(),
                ChineseAddressGenerator.getInstance().generate(),
                format);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(customer);
        logger.info("json对象:{}", json);
        // 准备request请求，指定文档id
        IndexRequest request = new IndexRequest(EsConfig.INDEX_NAME, EsConfig.TYPE, customer.getId());
        request.source(json, XContentType.JSON);
        // 通过client对象添加
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        logger.info("输出日志", response.getResult().toString());
    }

    /**
     * 批量创建文档
     */
    @Test
    public void bulkCreateDoc() throws IOException {
        // 封装批量对象
        BulkRequest request = new BulkRequest();
        for (int i = 0; i < 2000; i++) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String format = formatter.format(LocalDateTime.now());
            String idCard = ChineseIDCardNumberGenerator.getInstance().generate();
            Customer customer = new Customer(IdUtil.simpleUUID(),
                    ChineseNameGenerator.getInstance().generate(),
                    idCard,
                    idCard.charAt(idCard.length() - 2) % 2 == 0 ? "女" : "男",
                    IdcardUtil.getAgeByIdCard(idCard),
                    ChineseMobileNumberGenerator.getInstance().generate(),
                    ChineseAddressGenerator.getInstance().generate(),
                    format);
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(customer);
            IndexRequest indexRequest = new IndexRequest("user", EsConfig.TYPE, customer.getId()).source(json, XContentType.JSON);
            request.add(indexRequest);
        }
        // client执行批量增加
        BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
        logger.info("输出结果：{}", bulk.toString());
    }

    /**
     * 批量删除文档
     */
    @Test
    public void bulkDeleteDoc() throws IOException {
        // 创建批量对象
        BulkRequest request = new BulkRequest();
        // 添加删除文档对象
        request.add(new DeleteRequest(EsConfig.INDEX_NAME, "e46e11c5739f4c16b5a04c89d10ce26d"));
        request.add(new DeleteRequest(EsConfig.INDEX_NAME, "e46e11c5739f4c16b5a04c89d10ce26d"));
        // 执行操作
        BulkResponse delete = client.bulk(request, RequestOptions.DEFAULT);
        logger.info("输出结果:{}", delete.toString());
    }

    /**
     * 根据id修改指定字段
     */
    @Test
    public void updateDocFiled() throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张思");
        map.put("age", 30);
        String id = "7f9f5baa5f03404d88979977aa78337f";
        // 创建request，指定索引名称和id
        UpdateRequest request = new UpdateRequest(EsConfig.INDEX_NAME, id);
        request.doc(map);
        // 通过client执行
        UpdateResponse update = client.update(request, RequestOptions.DEFAULT);
        logger.info("输出更新结果:{}", update.getResult().toString());
    }

    /**
     * 指定id删除文档
     */
    @Test
    public void deleteDoc() throws IOException {
        String id = "93668bee867146aabc942140869d3b6a";
        // 封装request对象
        DeleteRequest request = new DeleteRequest(EsConfig.INDEX_NAME, id);
        // client执行
        DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
        // 输出结果
        logger.info("输出结果:{}", delete.getResult());
    }
}
